<template>
  <div class="goods-list-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名" prop="name">
          <el-input v-model="searchForm.username" autocomplete="off" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="商品分类" prop="roleId">
          <el-select v-model="searchForm.categoryId" placeholder="选择商品分类">
            <el-option v-for="option in goodsCategoryList" :key="option.id" :label="option.name" :value="option.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 清空 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-field">
      <div class="btns-fun-field">
        <el-button type="primary" @click.prevent="showAddEditDialog" :icon="Plus">
          新增商品
        </el-button>
      </div>
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="name" label="商品名" width="160" />
        <el-table-column prop="coverUrl" label="商品图" width="90">
          <template #default="scope">
            <el-image style="width: 60px;" 
              :preview-teleported="true" 
              :src="scope.row.coverUrl"
              :preview-src-list="[scope.row.coverUrl]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="商品类别" width="100" />
        <el-table-column prop="sn" label="商品编号" width="186" />
        <el-table-column prop="brandName" label="品牌" width="120" />

        <el-table-column prop="marketPrice" label="市场价" width="95">
          <template #default="scope">
            <span v-if="scope.row.marketPrice">{{ (scope.row.marketPrice / 100).toFixed(2) }} 元</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="cost" label="成本价" width="95">
          <template #default="scope">
            <span v-if="scope.row.cost">{{ (scope.row.cost / 100).toFixed(2) }} 元</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="actualPrice" label="销售价" width="95">
          <template #default="scope">
            <span v-if="scope.row.actualPrice">{{ (scope.row.actualPrice / 100).toFixed(2) }} 元</span>
            <span v-else>--</span>
          </template>
        </el-table-column>

        <el-table-column prop="viewCount" label="浏览量" width="86" />
        <el-table-column prop="buyCount" label="购买次数" width="86" />

        <el-table-column prop="store" label="库存" width="80" />

        <el-table-column prop="grounding" label="上架状态" width="85">
          <template #default="scope">
            <span v-if="scope.row.grounding == 1" style="color: darkgreen">已上架</span>
            <span v-else style="color: #f00">已下架</span>
          </template>
        </el-table-column>

        <el-table-column prop="allowGroupBuy" label="允许团购" width="85">
          <template #default="scope">
            <span v-if="scope.row.allowGroupBuy == 1" style="color: #f00">否</span>
            <span v-else style="color: darkgreen">是</span>
          </template>
        </el-table-column>

        <el-table-column prop="groupBuyDiscountTypeName" label="团购折扣" width="100">

        </el-table-column>

        <el-table-column prop="groupBuyDiscountName" label="折扣力度" width="100">

        </el-table-column>

        <el-table-column prop="sort" label="排序" width="60" />
        <el-table-column prop="delayTime" label="上架时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" min-width="220px" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.id != 1" type="success" size="small"
              @click.prevent="showAddEditDialog(scope.row, 2)">编辑</el-button>
              <el-button type="danger" v-if="scope.row.grounding==1" size="small" @click.prevent="showGroundingDialog(scope.row)">下架</el-button>
              <el-button type="primary" v-else size="small" @click.prevent="showGroundingDialog(scope.row)">上架</el-button>

              <el-button type="danger" size="small" @click.prevent="showRemoveDialog(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-field">
        <el-pagination v-model:current-page="formData.pageIndex" v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-if="removeDialogVisible" v-model="removeDialogVisible" title="删除商品" width="400px">
      <span>确定要删除当前商品？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveGoodsInfo"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-if="groundingDialogVisible" v-model="groundingDialogVisible" :title="`${curSelectRow.grounding == 1? '下架': '上架'}商品` " width="400px">
      <span>确定要{{ curSelectRow.grounding == 1 ? '下架': '上架' }}当前商品？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="groundingDialogVisible = false">取消</el-button>
          <el-button :type=" curSelectRow.grounding == 1? 'danger': 'primary'" @click="startGroundingGoodsInfo"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getGoodsPagination,
  removeGoodsInfo,
  getGoodsCategoryAllList,
  groundingGoodsInfo
} from "@/api/goods-manage.api";
import { Plus } from "@element-plus/icons-vue";
import { FormInstance, ElMessage } from "element-plus";
import { useRouter } from 'vue-router'
const $router = useRouter();
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

const searchForm = reactive({
  username: "",
  roleId: "",
});

const groupBuyDiscountTypeList=[
    {
        id: 0,
        name: "无优惠"
    },
    {
        id: 1,
        name: "金额直减"
    },
    {
        id: 2,
        name: "百分比折扣"
    }
]



const goodsCategoryList = ref([])
const requestoodsCategoryAllList = async ()=>{
  try {
    let res = await getGoodsCategoryAllList();
    goodsCategoryList.value = res;
  } catch (err){
    ElMessage({
        message: err.msg || err,
        type: "error",
      });
  }
}

const removeDialogVisible = ref(false);
const groundingDialogVisible = ref(false);
const addDialogVisible = ref(false);
const addEditRef = ref<FormInstance>();
const addEditForm = reactive({
  id: null,
  name: "",
  parentId: 0,
  level: 1,
  sort: 0,
  disabled: false,
  title: "",
  permissionList: [],
});
const addEditRules = reactive({
  name: [
    { required: true, message: "请输入商品名", trigger: "blur" },
    { min: 1, max: 30, message: "长度为1~30位", trigger: "blur" },
  ],
});

//获取商品权限列表


const showAddEditDialog = () => {
  $router.push("/goods/add")
};



const tableLoading = ref(false);
const tableData = ref([]);

const curSelectRow = ref({ id: '' });
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const showGroundingDialog = (item:any)=>{
  groundingDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
}

const startRemoveGoodsInfo = () => {

  let id = curSelectRow.value.id;
  removeGoodsInfo([id])
    .then((res) => {
      console.log("success~~~~~", res);
      removeDialogVisible.value = false;
      ElMessage({
        message: "商品删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      removeDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
};

const startGroundingGoodsInfo = ()=>{
  let goodsInfo = curSelectRow.value;
  let id = goodsInfo.id;
  let hint = goodsInfo.grounding == 1 ? '下架' : '上架'
  groundingGoodsInfo({
    goodsId: id,
    grounding: goodsInfo.grounding == 1 ? 0 : 1
  })
    .then((res) => {
      console.log("success~~~~~", res);
      groundingDialogVisible.value = false;
      ElMessage({
        message: `商品${hint}成功`,
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      groundingDialogVisible.value = false;
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
}


const startAddGoodsCategory = () => {
  console.log("...")
  let formData = {
    name: addEditForm.name,
    sort: addEditForm.sort,
    parentId: addEditForm.parentId,
    level: addEditForm.level
  };

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid) => {
    if (valid) {
      if (addEditForm.id) {
        updateGoodsCategory({
          ...formData,
          id: addEditForm.id,
        })
          .then((res) => {
            console.log(res)
            addDialogVisible.value = false;
            ElMessage({
              message: "商品修改成功",
              type: "success",
            });
            getDataList();
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: "error",
            });
          });
        return;
      }

      addGoodsCategory(formData)
        .then((res) => {
          console.log(res)
          addDialogVisible.value = false;
          ElMessage({
            message: "商品新增成功",
            type: "success",
          });
          getDataList();
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};

const getDataList = () => {
  tableLoading.value = true;
  getGoodsPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {

      tableLoading.value = false;
      let list = res.list || [];
      list = list.map( item=>{
        let findRes = goodsCategoryList.value.find( row=>{
          return item.categoryId == row.id;
        })
        if( findRes ){
          item.categoryName = findRes.name;
        }

        console.log("item.groupBuyDiscountType: ",item.groupBuyDiscountType)
        findRes = groupBuyDiscountTypeList.find((row)=>{
          return row.id+'' === item.groupBuyDiscountType+''
        })
        
        if( item.groupBuyDiscountType == 0){
          item.groupBuyDiscountName ='--'
        }else if(item.groupBuyDiscountType == 1){
          item.groupBuyDiscountName = '优惠 '+ (item.groupBuyDiscount/100).toFixed(2) + " 元"
        } else if(item.groupBuyDiscountType == 2){
          item.groupBuyDiscountName = (item.groupBuyDiscount/10).toFixed(2) + " 折"

        }

        if( findRes ){
          item.groupBuyDiscountTypeName = findRes.name;
        }
        return {
          ...item,

        }
      } )
      console.log(".......................");
      console.log(res);
      console.log(".......................");
      tableData.value = list;
      formData.total = Number(res.total);
    })
    .catch((error) => {
      console.log(error);
      tableLoading.value = false;
    });
};


onMounted(async () => {
  await requestoodsCategoryAllList();
  getDataList();
});
</script>
<style lang="scss" scoped>
@import "./GoodsList.scss"
</style>
